from flask import Flask, request, jsonify, send_from_directory, render_template, redirect, url_for
import os
import startcode
import sys
import pose_recognition as pr
import base64
import io
import cv2
import numpy as np
from PIL import Image
from matplotlib.animation import FuncAnimation
from flask_cors import CORS
from threading import Thread
from flask_socketio import SocketIO
from celery import Celery
from Celery_app import make_celery, celery
import photo2video as p2v

video_path = ""
side = 0
height_real = 0

app = Flask(__name__)
CORS(app)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)


# 创建一个文件夹invideo，用来存放用户上传的视频
app.config['INVIDEO_FOLDER'] = 'invideo'
if not os.path.exists(app.config['INVIDEO_FOLDER']):
    os.makedirs(app.config['INVIDEO_FOLDER'])

# pose_data = {
#     'attacks_count': 0,
#     'sum_distance': 0,
#     'right_hand_angle': 0,
#     'right_ankle_angle': 0,
#     'left_ankle_angle': 0,
#     'right_knee_angle': 0,
#     'left_knee_angle': 0,
#     'right_shoulder': (0, 0),
#     'left_shoulder': (0, 0),
#     'right_hip': (0, 0),
#     'left_hip': (0, 0),
#     'img_base64': '',
#     'standardaction': '',
#     'action': ''
# }


# 访问根目录时，调用index()函数
@app.route('/')
def index():
    return render_template('index.html')



@app.route('/data', methods=['GET'])
def data():
    # 这里需要实现从后端获取数据的逻辑
    # 例如，从全局变量或数据库中获取数据
    data = {
        'attacks_count':     pr.attacks_count,  # 示例数据
        'sum_distance':      pr.global_sum_distance,
        'right_hand_angle':  pr.global_right_hand_angle,
        'right_ankle_angle': pr.global_right_ankle_angle,
        'left_ankle_angle':  pr.global_left_ankle_angle,
        'right_knee_angle':  pr.global_right_knee_angle,
        'left_knee_angle':   pr.global_left_knee_angle,
        'right_shoulder':    pr.global_right_shoulder,
        'left_shoulder':     pr.global_left_shoulder,
        'right_hip':         pr.global_right_hip,
        'left_hip':          pr.global_left_hip,
        'img_base64':        pr.img_base64,
        'standardaction':    pr.standardaction,
        'action':            pr.action
    }
    return jsonify(data)
    

@app.route('/upload', methods=['POST'])
def upload_video():
    video = request.files.get('video')
    side = request.form.get('side', type=int)
    height = request.form.get('height', type=int)
    button_type = request.form.get('button_type')
    file_type = request.form.get('file_type')
    if not video:
        return jsonify({'error': 'No video file uploaded'}), 400
    
    if button_type == 'competition' and not file_type.startswith('video/'):
        return jsonify({'error': '比赛分析只能上传视频文件'}), 400

    if button_type == 'analysis' and not file_type.startswith('image/'):
        return jsonify({'error': '动作分析只能上传照片文件'}), 400


    video_path = os.path.join(app.config['INVIDEO_FOLDER'], video.filename)
    video.save(video_path)
    absolute_video_path = os.path.abspath(video_path)
    return jsonify({
        'video_path': absolute_video_path,
        'side': side,
        'height': height,
        'button_type': button_type
    })


@app.route('/competition')
def competition():
    try:
        video_path = request.args.get('video_path')
        side = int(request.args.get('side'))
        height = int(request.args.get('height'))
        if not video_path or not os.path.exists(video_path):
            return "Invalid video path", 400
        thread = Thread(target=startcode.startcode, args=(video_path, side, height))
        thread.start()
        return render_template('competition.html')
    except Exception as e:
        app.logger.error(f"Error in competition route: {e}")
        return "Internal Server Error", 500

@app.route('/analysis')
def analysis():
    try:
        video_path = request.args.get('video_path')
        side = int(request.args.get('side'))
        height = int(request.args.get('height'))
        print(video_path)
        output_videoPath = 'invideo'
        video_path = p2v.photo_to_video(video_path, output_videoPath)
        print(f"111{video_path}")
        thread = Thread(target=startcode.startcode_two, args=(video_path, side, height))
        thread.start()
        # startcode.startcode.delay(video_path, side, height)
        return render_template('analysis.html')
    except Exception as e:
        app.logger.error(f"Error in competition route: {e}")
        return "Internal Server Error", 500


@app.route('/report')
def report():
    return render_template('report.html')


# @app.route('/download_report')
# def download_report():
#     # 生成 PDF 报告
#     from fpdf import FPDF
#     pdf = FPDF()
#     pdf.add_page()
#     pdf.set_font("Arial", size=15)
#     pdf.cell(200, 10, txt="姿态识别报告", ln=True, align='C')
#     pdf.set_font("Arial", size=12)
#     pdf.cell(200, 10, txt=f"进攻次数: {pose_data['attacks_count']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"移动距离: {pose_data['sum_distance']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"右手夹角: {pose_data['right_hand_angle']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"右脚夹角: {pose_data['right_ankle_angle']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"左脚夹角: {pose_data['left_ankle_angle']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"右膝夹角: {pose_data['right_knee_angle']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"左膝夹角: {pose_data['left_knee_angle']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"右肩坐标: {pose_data['right_shoulder']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"左肩坐标: {pose_data['left_shoulder']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"右臀坐标: {pose_data['right_hip']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"左臀坐标: {pose_data['left_hip']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"动作标准度: {pose_data['standardaction']}", ln=True, align='L')
#     pdf.cell(200, 10, txt=f"动作类型: {pose_data['action']}", ln=True, align='L')
#     pdf.output("report.pdf")
#     return send_from_directory(directory='.', path='report.pdf', as_attachment=True)



if __name__ == '__main__':
    host_address = '127.0.0.1'  # 监听本地请求
    # 使用4090端口
    host_port = 5000
    print(f"访问本地服务器地址: http://{host_address}:{host_port}")
    # 运行app应用
    app.run(debug=True, host=host_address, port=host_port)
